#!/usr/bin/python3
"""_summary_

    Returns:
        _type_: _description_
"""
# -*- coding:utf-8 -*-
#
# File Name:
# @Author:  paddy
# @Email:   3988263@qq.com
# @Time:    ${DATE} ${TIME}
# Project: ${PROJECT_NAME}
# ---------------------说明--------------------------
#
# ---------------------------------------------------
import logging
from service.base import MyBase
from utils.tools import Tools

logger = logging.getLogger(__name__)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(console)


class Business(MyBase):
    """主要是初始化并添加到线上，创建所有用例数据和删除所有数据

    Returns:
        _type_: _description_
    """

    # 创建组时，将设备的上一级组id保存这里，为了批量创建设备使用，并可以保存到json中
    device_asset_id = []
    # 添加设备时，将设备id保存这里，并可以保存到json中
    device_id = []

    def cerate_entrying(self):
        """初始化并创建所有数据
        """
        # 如果没有数据，创建个项目，然后这里主要加载本地json数据，再创建数据
        # 如果有数据则跳过创建数据
        if not self.check_ishave_data():
            self._business_add()
            self._load_asset_modules()
            self._load_device_module()
            # 下面开始实际创建
            self.create_data()
            self.batch_device()

    # 添加项目
    def _business_add(self):
        """添加项目,并将项目返回结果保存为self.business
        """
        _data = {
            "name": self.local_business_name
        }
        status_code, message = self.webapi.api_business_add(_data)
        if status_code == 200:
            self.set_business_data(message['data'])
            self._getbusiness_asset_id()

    # #添加设备分组
    def asset_add(self, asset_name, parent_id, tier=None):
        """_summary_

        Args:
            asset_name (_type_): _description_
            parent_id (_type_): _description_
            tier (_type_): _description_
        """
        _data = {

            "business_id": self.business['id'],
            "name": asset_name,
            "parent_id": parent_id,
            "tier": tier,
        }
        return self.webapi.api_asset_add_only(_data)

    # 删除business_id所有数据
    def _clean_business_data(self, business_id):
        """删除所有数据
        """
        data = {
            "id": business_id
        }
        status_code, message = self.webapi.api_business_delete(data)
        if status_code == 200:
            logger.info(
                "业务%s删除完毕,下所有数据清除",
                business_id
                )
        else:
            logger.error(message)

    def clear_all_data(self):
        """查询所有业务，并循环删除
        """
        data = {
            "name": self.local_business_name,
            "limit": 0,
            "page": 0
        }
        status_code, message = self.webapi.api_business_index(data)
        if status_code == 200:
            if len(message['data']['data']) > 0:
                for _bussiness in message['data']['data']:
                    self._clean_business_data(_bussiness['id'])
        else:
            logger.error(message)

    # 创建所有数据
    def create_data(self):
        """创建所有数据
        """
        self.iter_asset_add(self.local_asset_data, self.business['asset_id'])
        # 将设备组数据保存到本地json文件
        if len(self.device_asset_id) > 0 and len(self.device_asset_id) > 0:
            tools = Tools()
            tools.writejson('device_asset_id.json', self.device_asset_id)

    def iter_asset_add(self, node, parent_id=None):
        """批量循环添加组

        Args:
            node (_type_): _description_
        """
        if 'tier' in node:
            status_code, message = self.asset_add(
                    node['name'], parent_id, node['tier']
                )
            if status_code == 200:
                parent_id = message['data']['id']  # 获得循环下一层parent_id
            if 'asset' in node:
                for subnode in node['asset']:  # 循环下一层asset
                    self.iter_asset_add(subnode, parent_id)
        else:  # 最后一层没有 tier
            status_code, message = self.asset_add(
                node['name'], parent_id
            )
            if status_code == 200:
                # print(message)
                # 把设备需要的asset_id保存下来
                self.device_asset_id.append(message['data']['id'])

    def add_device(self, asset_id, device_module, parent_id=None):
        """批量添加组目录树
        """
        # logger.info(sys._getframe().f_code.co_name)
        location = ','.join([str(device_module['longitude']),
                            str(device_module['latitude'])])
        data = {
            "id": "",
            "asset_id": asset_id,
            "token": "",
            "device_type": str(device_module['type']),
            "name": device_module['name'],
            "extension": "",
            "protocol": device_module['protocol'],
            "d_id": "",
            "parent_id": parent_id,
            "location": location,
            "device_state": "0"
        }
        status_code, message = self.webapi.api_device_add_only(data)
        if status_code == 200:
            device_id = message['data']['id']
            self.device_id.append(device_id)
            # 将self.device_id添加到当前设备的token中
            self.edit_device_token(device_id, device_id)
        else:
            print(message)

    @property
    def get_device_id(self) -> list:
        """_summary_

        Returns:
            _type_: _description_
        """
        return self.device_id

    def edit_device_token(self, device_id, token) -> None:
        """ 修改设备token
        """
        data = {
            "id": device_id,
            "token": token,
            "protocol": ""

        }
        status_code, message = self.webapi.edit_device_token(data)
        if status_code == 200:
            print(message)
        else:
            logger.error(message)

    def batch_device(self):
        """对所有最后节点批量循环增加设备
        """
        for asset_id in self.device_asset_id:
            self.add_device(asset_id, self.local_device_module)
        # 将设备添加后获得的device_id保存到本地json文件
        if self.device_id and len(self.device_id) > 0:
            # 保存self.device_id到json文件中
            tools = Tools()
            tools.writejson('device_id.json', self.device_id)
